package com.jimmy.medical.repository;

import com.jimmy.medical.entity.FlowOrder;
import com.jimmy.medical.entity.Member;
import com.jimmy.medical.entity.RechargeRecord;
import com.jimmy.medical.entity.User;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;

@Repository
public interface FlowOrderRepository extends JpaSpecificationExecutor<FlowOrder>, PagingAndSortingRepository<FlowOrder, Long> {

    List<FlowOrder> findByUser(User user);

    //只查询未支付的
    @Query("select r from RechargeRecord r where r.member=?1 and r.rechargeType=?2 and r.createTime<=?3 and status<>?4")
    List<RechargeRecord> findMemberRechargeRecord(Member member, String rechargeType, String time, String status);

    @Query(value = "select count(*),flowOrderType.id,orderType.id from FlowOrder where isAssign=0 group by flowOrderType.id,orderType.id")
    List<Object[]> findAllUnassigned();

    @Query(value = "select count(*),f.flowOrderType.id,f.orderType.id from FlowOrder f left join f.order o left join o.hospital h where h.id=?1 and isAssign=0 group by f.flowOrderType.id,f.orderType.id")
    List<Object[]> findUnassignedByHospital(Long hospitalId);

    @Query(value = "select f from FlowOrder f left join f.user u where u.id=?1 and f.isFinish=?2")
    List<FlowOrder> findUnFinishedByUser(Long userId, Short isFinish);

    @Query(value = "select sum(money) from FlowOrder where user.id=?1 and updateTime>=?2 and isFinish=?3")
    Double sumByUser(Long userId, Date startTime, Short isFinish);

    @Query(value = "select count(*) from FlowOrder where user.id=?1 and updateTime>=?2 and isFinish=?3")
    int countByUser(Long userId, Date startTime, Short isFinish);

    List<FlowOrder> findAllByUserAndIsFinishOrderByCreateTimeDesc(User user, Short isFinish);
}
